package top.yangbuyi.config.shiro;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yangbuyi.constants.HttpStatus;
import top.yangbuyi.vo.AjaxResult;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


/**
 * @description: 杨不易网站:www.yangbuyi.top
 * @program: yangbuyiopenHis2020
 * @ClassName: ShiroLoginFilter
 * @create: 2020-08-27 23:58
 * @author: yangbuyi
 * @since： JDK1.8
 * @ShiroLoginFilter: Shiro登录过滤器$判断用户是否登录了
 **/

public class ShiroLoginFilter extends FormAuthenticationFilter {

	  /**
	   * 在访问controller前判断是否登录，返回json，不进行重定向。
	   * @param request
	   * @param response
	   * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
	   * @throws Exception
	   */
	  @Override
	  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.setContentType("application/json");
			AjaxResult ajaxResult=AjaxResult.fail();
			ajaxResult.put("code", HttpStatus.UNAUTHORIZED);
			ajaxResult.put("msg", "非法访问：登录认证失效，请重新登录!");
			httpServletResponse.getWriter().write(JSON.toJSON(ajaxResult).toString());
			return false;
	  }

}
